//
//  LJWebKitSupport.m
//  Onskysell
//
//  Created by LJJ on 2017/8/11.
//  Copyright © 2017年 cg. All rights reserved.
//

#import "LJWebKitSupport.h"

@interface LJWebKitSupport ()

@end

@implementation LJWebKitSupport
+ (instancetype)sharedSupport {
    static LJWebKitSupport *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [LJWebKitSupport new];
    });
    return  _instance;
}

- (instancetype)init {
    if (self = [super init]) {
        self.processPool = [WKProcessPool new];
        self.webViewConfiguration = [WKWebViewConfiguration new];
        self.contentController = [WKUserContentController new];
        self.webViewConfiguration.userContentController = self.contentController;
        self.webViewConfiguration.processPool = self.processPool;
//        self.webViewConfiguration.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
    }
    return self;
}

+ (WKWebView *)createSharableWKWebView {
    
    WKUserContentController* userContentController = [WKUserContentController new];
    
    NSMutableString *cookies = [NSMutableString string];
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[cookies copy]
                                                         injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                                      forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    
    WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
    // 一下两个属性是允许H5视屏自动播放,并且全屏,可忽略
    configuration.allowsInlineMediaPlayback = YES;
    configuration.mediaPlaybackRequiresUserAction = NO;
    // 全局使用同一个processPool
    configuration.processPool = [[LJWebKitSupport sharedSupport] processPool];
    configuration.userContentController = userContentController;
    
    WKWebView *wk_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    
    return wk_webView;
}

#pragma mark - 拼接cookie
+ (NSString*)readCurrentCookieWith:(NSDictionary*)dic{
    if (dic == nil) {
        return nil;
    }else{
        NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSMutableString *cookieString = [[NSMutableString alloc] init];
        for (NSHTTPCookie*cookie in [cookieJar cookies]) {
            [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
        }
        //删除最后一个“；”
        [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
        return cookieString;
        
    }
}

+ (NSString *)getCookieJsonWithCookiesArr:(NSArray *)cookies
{
    if (cookies.count <= 0) {
        return nil;
    }
    else
    {
        NSString *jsonStr = [cookies componentsJoinedByString:@","];
        return jsonStr;
    }
}

@end
